import 'package:flutter/material.dart';
import 'package:top_foundation/utils/util.dart';

class WheelListView extends StatefulWidget {
  const WheelListView({
    Key? key,
    required this.list,
    this.value,
    required this.valueChanged,
    this.isLoop = true,
  }) : super(key: key);
  final List<String> list;
  final String? value;
  final ValueChanged<String> valueChanged;
  final bool isLoop;
  @override
  State<WheelListView> createState() => _WheelListViewState();
}

class _WheelListViewState extends State<WheelListView> {
  int currIndex = -1;
  late FixedExtentScrollController sc;
  @override
  void initState() {
    initialization();
    super.initState();
  }

  @override
  void dispose() {
    sc.dispose();
    super.dispose();
  }

  void initialization() {
    if (widget.value != null) {
      currIndex = widget.list.indexOf(widget.value!);
    } else if (widget.list.length == 1) {
      currIndex = 0;
    }
    sc = FixedExtentScrollController(initialItem: currIndex);
  }

  Widget _cell(int index, String e) {
    return InkWell(
      onTap: () {
        if (currIndex == index) return;
        currIndex = index;
        sc.jumpToItem(currIndex);
      },
      child: Container(
        alignment: Alignment.center,
        child: Text(
          e,
          style: TextStyle(
            color: const Color(0xff333333),
            fontSize: 15.sp,
          ),
        ),
      ),
    );
  }

  List<Widget> _children() {
    return widget.list
        .asMap()
        .map((index, e) {
          return MapEntry(index, _cell(index, e));
        })
        .values
        .toList();
  }

  @override
  Widget build(BuildContext context) {
    return ListWheelScrollView.useDelegate(
      controller: sc,
      itemExtent: 50.h,

      diameterRatio: 5, //半径
      perspective: 0.01, //倾斜度
      overAndUnderCenterOpacity: 0.5, //透明度
      useMagnifier: true,
      magnification: 1.2, //放大倍数
      // squeeze: 0.5,//间距
      physics: const FixedExtentScrollPhysics(),
      onSelectedItemChanged: (index) {
        var val = widget.list[index];
        widget.valueChanged(val);
      },
      childDelegate: widget.isLoop
          ? ListWheelChildLoopingListDelegate(children: _children())
          : ListWheelChildBuilderDelegate(
              builder: (context, index) {
                var e = widget.list[index];
                return _cell(index, e);
              },
              childCount: widget.list.length,
            ),
    );
  }
}
